<?php

/**
 * Card class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Friday, July 15, 2011. 09:38 AM
 */
class Card extends CModel {
	public $insertTime;
	public $updateTime;
	public $name;
	public $code;
	public $birthPlace;
	public $birthDate;
	public $gender;
	public $address;
	public $expireDate;
	public $photoId;
	public $photoExtension;
	public $title;

	public static function find($code) {
		$member = Member::model()->find('code=:code', array(':code'=>$code));
		if (!$member) return null;

		$self = new self;
		$self->insertTime = $member->insertTime;
		$self->updateTime = $member->updateTime;
		$self->code = $member->code;
		$self->name = $member->name;
		$self->birthPlace = $member->birthPlace;
		$self->gender = $member->gender;
		$photo = $member->photo;
		if ($photo) {
			if ($self->updateTime < $photo->updateTime) {
				$self->updateTime = $photo->updateTime;
			}
			$self->photoId = $photo->_id;
			$self->photoExtension = $photo->extension;
		}
		$homeAddress = $member->homeAddress;
		if ($homeAddress) {
			if ($self->updateTime < $homeAddress->updateTime) {
				$self->updateTime = $homeAddress->updateTime;
			}
			$data = array(
				$homeAddress->street,
				$homeAddress->city,
				$homeAddress->postalCode,
			);
			$line1 = implode(' ', $data);
			$data = array(
				$homeAddress->province,
				'Indonesia',
			);
			$line2 = implode(' ', $data);
			$address = implode("\r\n", array($line1, $line2));
			$self->address = $address;
		}
		$expireDate = $member->expireDate;
		if ($expireDate) {
			if ($self->updateTime < $expireDate->updateTime) {
				$self->updateTime = $expireDate->updateTime;
			}
			$formatter = Yii::app()->dateFormatter;
			$date = date('Y-m-d', $expireDate->value);
			$date = $formatter->formatDateTime($date, 'long', null);
			$self->expireDate = $date;
		}
		$birthDate = $member->birthDate;
		if ($birthDate) {
			if ($self->updateTime < $birthDate->updateTime) {
				$self->updateTime = $birthDate->updateTime;
			}
			$formatter = Yii::app()->dateFormatter;
			$date = date('Y-m-d', $birthDate->value);
			$date = $formatter->formatDateTime($date, 'long', null);
			$self->birthDate = $date;
		}
		$title = $member->senkomTitle;
		if ($title) {
			if ($self->updateTime < $title->updateTime) {
				$self->updateTime = $title->updateTime;
			}
			$self->title = $title->position ? $title->position : 'Anggota';
		} else {
			$self->title = 'Anggota';
		}

		return $self;
	}

	public function attributeNames() {
		return array(
			'insertTime',
			'updateTime',
			'name',
			'code',
			'birthPlace',
			'birthDate',
			'gender',
			'address',
			'expireDate',
			'photoId',
			'photoExtension',
			'title',
		);
	}
}
